package top.ply.userservice.aop;

import org.apache.dubbo.config.annotation.DubboReference;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.util.StringUtils;
import top.ply.authservice.service.CommonAuthService;
import top.ply.common_unit.entity.RespEntity;
import top.ply.common_unit.global_resp.RespUtil;

import java.util.HashMap;
import java.util.Map;

@Aspect
public class CommonUserServiceAop {

    @DubboReference(interfaceClass = CommonAuthService.class)
    CommonAuthService commonAuthService;

    @Pointcut("execution(* top.ply.userservice.service.impl.CommonUserServiceImpl.* (..))")
    void commonUserServiceAllMethodPointcut() {}

    @AfterReturning(value = "commonUserServiceAllMethodPointcut()", returning = "respEntity")
    public Object afterAllMethodReturned(ProceedingJoinPoint joinPoint, RespEntity respEntity) {
        Object[] args = joinPoint.getArgs();
        if (RespUtil.GLOBAL_SUCCESS_CODE.equals(respEntity.getCode())) {
            if (respEntity.getData() == null) {
                respEntity.setData(new HashMap<String, Object>());
            }
            if (args[0] instanceof String) {
                String token = commonAuthService.refreshToken((String) args[0]);
                if (StringUtils.hasText(token)) {
                    respEntity.getData().put("token", token);
                }
            }
        }
        return respEntity;
    }

}
